<?php

namespace Sys;

use C\L\AdmController;
use C\M\SysConfig;
use C\M\WithdrawLog;
use C\M\UserInvest;

class ConfigController extends AdmController
{

  //获取信息
    public function infoAction()
    {
        $type = $this->getValue('type', true);
        $config = $this->s_config->get($type);
        if (empty($config)) {
            $this->error('未找到相关配置');
        }

        if ($type == 'anwser') {
            $config['vips'] = $this->s_level->searchAll([], [], ['name', 'id']);
        }

        $this->success($config);
    }

  //更新
    public function updateAction()
    {
        $type = $this->getValue('type', true);
        $config = $this->s_config->search(['type' => $type]);
        if (empty($config)) {
            $this->firstConfig($type, []);
            $this->error('未找到相关配置');
        }

        $content = json_decode(file_get_contents('php://input'), true);
        unset($content['type']);
        unset($content['ssid']);

      // $content = json_decode($config['content'], true);
        foreach ($content as $k => $v) {
            $value = $this->getValue($k);

            if (strstr($k, 'vip') ||
            in_array($k, ['content', 'banner', 'question', 'remark', 'aprs', 'contract_content', 'prize'])
            ) {
                $value = $this->request->getPost($k);
            }

            if ($k == 'prize') {
                $num = 0;
                foreach ($value as &$p) {
                    $p['pro'] = bcadd($p['pro'], 0, 2);
                    $num += $p['pro'];
                }

                if ($num != 100) {
                    $this->error('总中奖概率要为100%');
                }
            }

            if ($value !== null) {
                $content[$k] = $value;
            }
        }

        if ($type == 'anwser' && empty($content['no'])) {
            $content['no'] = md5(time());
        }

        if ($type == 'sales_random') {
            $s = $this->getValue('status');
            $content['status'] = $s;
            if (!in_array($content['status'], ['Y', 'N'])) {
                $this->error('参数错误');
            }
        }

        if ($this->s_config->update($config['id'], ['content' => json_encode($content)])) {
            $this->success();
        }

        $this->error();
    }

  /**
   * 后续替换 updateAction
   **/
    public function newUpdateAction()
    {
        $type    = $this->getValue('type', true);
        $content = $this->getValue('content', true);

        $config = SysConfig::findFirst([
        'conditions' => 'type = :type:',
        'bind' => [
        'type' => $type,
        ],
        ]);

        if (!$config) {
            $config = new SysConfig;
            $config->type = $type;
        }

        $config->content = $content;

        $config->save()
        ? $this->success()
        : $this->error();
    }

    public function audioAction()
    {
        $config = $this->s_config->get('sound');

        $withdrawLog = WithdrawLog::findFirst([
        'conditions' => 'state = :state:',
        'bind' => ['state' => 'pending'],
        ]);

        $recharge = UserInvest::findFirst([
        'conditions' => 'status = :status:',
        'bind' => ['status' => 'S'],
        ]);

        $data = [
        'invest_sound' => $config['is_open_invest'] == 'Y' && $recharge,
        'cost_sound'   => $config['is_open_cost'] == 'Y' && $withdrawLog,
        ];

        $this->success($data);
    }

    public function indexAction()
    {
        $ydayTime   = strtotime(date('Ymd') . ' -1 day');
        $today = date('Y-m-d');
        $yesterday = date(
            'Y-m-d',
            mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"))
        );

        $todayWithdrawSum = WithdrawLog::sum([
        'conditions' => 'state = :state: AND created_at >= :start_date:',
        'bind'       => [
        'state'      => 'success',
        'start_date' => $today . ' 00:00:00',
        ],
        'column'     => 'amount',
        ]) ?? 0;

        $yesterdayWithdrawSum = WithdrawLog::sum([
        'conditions' => 'state = :state: AND created_at >= :start_date: AND created_at < :end_date:',
        'bind'       => [
        'state'      => 'success',
        'start_date' => $yesterday . ' 00:00:00',
        'end_date'   => $today . ' 00:00:00',
        ],
        'column'     => 'amount',
        ]) ?? 0;

        $allWithdrawSum = WithdrawLog::sum([
        'conditions' => 'state = :state:',
        'bind'       => ['state' => 'success'],
        'column'     => 'amount',
        ]) ?? 0;

        $data = [
        // 总会员
        'user_num' => $this->s_user->getCount(),

        // 今日充值次数
        'today_farm_count' => 0,

        // 今日充值
        'today_invest_sum' => $this->s_invest->getSum(
            'money',
            ['addtime' => strtotime(date('Ymd')), 'status' => 'Y'],
            ['addtime' => '>']
        ),
        // 今日提现
        'today_cost_sum' => $todayWithdrawSum,
        // 今日注册人数
        'today_reg_num' => $this->s_user->getCount(
            ['addtime' => strtotime(date('Ymd'))],
            ['addtime' => '>']
        ),
        // 昨日充值
        'yday_invest_sum' => $this->s_invest->getSum(
            'money',
            ['addtime' => [$ydayTime, $ydayTime + 24 * 3600 - 1], 'status' => 'Y'],
            ['addtime' => 'between']
        ),
        // 昨日提现
        'yday_const_sum' => $yesterdayWithdrawSum,
        // 昨日注册
        'yday_reg_num' => $this->s_user->getCount(
            ['addtime' => [$ydayTime, $ydayTime + 24 * 3600 - 1]],
            ['addtime' => 'between']
        ),
        // 今日签到
        'today_login_num' => $this->s_signin->getCount(
            ['addtime' => [strtotime(date('Ymd')), strtotime(date('Ymd')) + (24 * 3600) - 1]],
            ['addtime' => 'between']
        ),
        'all_invest_sum' => $this->s_invest->getSum('money', ['status' => 'Y']),
        'all_cost_sum'   => $allWithdrawSum,
        ];

        $this->success($data);
    }

    public function setmaintainAction()
    {
        $status = $this->getValue('status', true, 'string');
        if ($status == 'Y') {
            $this->cache->set('web_is_maintain', 1);
            $this->success([
            'is_maintain' => true
            ]);
        } else {
            $this->cache->set('web_is_maintain', 0);
            $this->success([
            'is_maintain' => false
            ]);
        }
    }

    public function firstConfig($type, $content)
    {
        if ($type == 'overview' && empty($content['ovvalue'])) {
            $content['ovvalue'] = $this->getValue('ovvalue', true, 'string');
            $add = [];
            $add['type'] = 'overview';
            $add['content'] = json_encode($content);
            $add['addtime'] = $add['uptime'] = time();
            $r = $this->s_config->save($add);
            if ($r) {
                $this->success();
            }
        }
    }
}
